package org.someone.common;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Key;
import java.util.Properties;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class CipherTools {
	public static byte[] encrypt(byte[] content, String pin) throws Exception {
		return toCipher(content, pin, Cipher.ENCRYPT_MODE);
	}
	
	public static byte[] decrypt(byte[] content, String pin) throws Exception {
		return toCipher(content, pin, Cipher.DECRYPT_MODE);
	}
	
	public static byte[] toCipher(byte[] content, String pin, int CipherMode) throws Exception {
		byte[] result = null;
		InputStream is = CipherTools.class
				.getResourceAsStream("CipherTools.properties");
		if (is != null) {
			Properties props = new Properties();
			props.load(new InputStreamReader(is,"UTF-8"));
			String algorithm = props.getProperty("algorithm");
			Cipher cipher = Cipher.getInstance(algorithm);
	        Key key = new SecretKeySpec(pin.getBytes(), algorithm); 
	        cipher.init(CipherMode, key);
	        result = cipher.doFinal(content);
			is.close();
		}
		return result;
	}
    
    public static String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		// 每个byte用两个字符才能表示，所以字符串的长度是数组长度的两倍
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			// 把负数转换为正数
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			// 小于0F的数需要在前面补0
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}
    
    public static byte[] hexStr2ByteArr(String strIn) throws Exception {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;

		// 两个字符表示一个字节，所以字节数组长度是字符串长度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}
}
